package com.ikun.starters.ip2region.impl;

import com.ikun.starters.ip2region.IP2regionService;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

/**
 * @ClassName IP2regionServiceImpl
 * @Description:
 * @Author: ximeng
 * @CreateDate: 2024/1/20 16:11
 * @UpdateUser:
 * @UpdateDate: 2024/1/20 16:11
 * @UpdateRemark:
 * @Version: 1.0
 */
@Slf4j
public class IP2regionServiceImpl implements IP2regionService {
    public String parsePublicIpPath;
    private String dbPath;

    public IP2regionServiceImpl(String parsePublicIpPath, String dbPath) {
        this.dbPath = dbPath;
        this.parsePublicIpPath = parsePublicIpPath;
    }


    private String loadDbPath() {
        // 使用 ClassLoader 加载资源文件路径
        String path = this.getClass().getClassLoader().getResource(dbPath).getPath();
        return path;
    }

    @Override
    public String getPublicIP() {
        try {
            URL url = new URL(parsePublicIpPath);
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String publicIP = reader.readLine();
            reader.close();
            log.info("公网ip:{ }" + publicIP);
            return publicIP;
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public String parseIp(String ip) {
        // 1、从 dbPath 中预先加载 VectorIndex 缓存，并且把这个得到的数据作为全局变量，后续反复使用。
        byte[] vIndex;
        String path = loadDbPath();

        try {
            vIndex = Searcher.loadVectorIndexFromFile(path);

            // 2、使用全局的 vIndex 创建带 VectorIndex 缓存的查询对象。
            String IpAddr = null;
            Searcher searcher;
            searcher = Searcher.newWithVectorIndex(path, vIndex);
            try {
                String region = searcher.search(ip);//中国|0|四川省|南充市|电信
                IpAddr = buildIpAddr(region);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                searcher.close();
            }
            return IpAddr;
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }

    }


    private String buildIpAddr(String region) {
        String[] split = region.split("\\|");
        StringBuilder sb = new StringBuilder();
        return sb.append(split[0]).append("-").append(split[2]).append("-").append(split[3]).append("|").append(split[4]).toString();
    }


}
